package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceReportVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备Service业务层处理
 * 
 * @author ljc
 * @date 2025-03-06
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {

        return deviceMapper.selectDeviceList(device);
    }
    /**
     * 新增设备
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    @Override
    public List<ServiceCapability>  queryProduct(String productKey) {
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        try {
            //调用华为云接口查询产品信息
            ShowProductResponse showProductResponse = client.showProduct( showProductRequest);
            List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
            if (CollUtil.isEmpty(serviceCapabilities)){
                return new ArrayList<>();
            }
            return serviceCapabilities;
        } catch (Exception e) {
            throw new BaseException("查询产品失败");
        }
    }

    @Override
    public void deleteByIotId(String iotId) {
        //删除云端设备
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.withDeviceId(iotId);
        try {
            DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
            if (deleteDeviceResponse.getHttpStatusCode()!=204){
                throw new BaseException("删除设备失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("删除设备失败");
        }
        //删除数据库设备
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId,iotId);
        deviceMapper.delete(queryWrapper);


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDevice(DeviceDto deviceDto) {
        //更新设备
        UpdateDeviceRequest updateDeviceRequest = new UpdateDeviceRequest();
        updateDeviceRequest.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret secret = new AuthInfoWithoutSecret();
        secret.withSecureAccess(true);
        body.setAuthInfo(secret);
        body.setDescription(deviceDto.getRemark());
        body.setDeviceName(deviceDto.getDeviceName());
        updateDeviceRequest.setBody(body);
        try {
            UpdateDeviceResponse response = client.updateDevice(updateDeviceRequest);
            if (response.getHttpStatusCode()!=200){
                throw new BaseException("更新设备失败");
            }
        }catch (Exception e){
            throw new BaseException("更新设备失败");
        }
        Device bean = BeanUtil.toBean(deviceDto, Device.class);
        updateById(bean);
    }

    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        //从云端平台获取设备数据
        ShowDeviceShadowRequest shadowRequest = new ShowDeviceShadowRequest();
        shadowRequest.withDeviceId(iotId);
        ShowDeviceShadowResponse shadowResponse = null;
        try {
            shadowResponse= client.showDeviceShadow(shadowRequest);
            if (shadowResponse.getHttpStatusCode()!=200){
                throw new BaseException("查询设备详情失败");
            }
        }catch (Exception e){
            throw new BaseException("查询设备详情失败");
        }
        ArrayList<DeviceReportVo> list = new ArrayList<>();
        List<DeviceShadowData> shadow = shadowResponse.getShadow();

        if (ObjectUtil.isEmpty(shadow)){
           return AjaxResult.success(new ArrayList<>());
        }
        //
        DeviceShadowData deviceShadowData = shadow.get(0);
        if (ObjectUtil.isNull(deviceShadowData)){
            return AjaxResult.success(new ArrayList<>());
        }
        String eventTimeStr = deviceShadowData.getReported().getEventTime();
        Object properties = deviceShadowData.getReported().getProperties();
        if (properties instanceof Map){
            Map<String, Object> propertiesMap = (Map<String, Object>) properties;
            propertiesMap.forEach((k,v)->{
                LocalDateTime dateTime = LocalDateTimeUtil.parse(eventTimeStr,"yyyyMMdd'T'HHmmss'Z'");
                LocalDateTime time = dateTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
              list.add(new DeviceReportVo(k,time,v.toString()));
            });
        }

        return AjaxResult.success(list);
    }

    @Override
    public DeviceDetailVo getByIotId(String iotId) {
        //查询数据库有无设备信息
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (ObjectUtil.isEmpty(device)){
            throw new BaseException("设备不存在");
        }
        //查询云端设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = null;
        try {
            showDeviceResponse = client.showDevice(request);
            if (showDeviceResponse.getHttpStatusCode()!=200){
                throw new BaseException("查询设备详情失败");
            }
        }catch (Exception e){
            throw new BaseException("查询设备详情失败");
        }
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        detailVo.setDeviceStatus(showDeviceResponse.getStatus());
        String activeTime = showDeviceResponse.getActiveTime();
        if (StrUtil.isNotBlank(activeTime)){
            LocalDateTime dateTime = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            LocalDateTime time = dateTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            detailVo.setActiveTime(time);
        }
        return detailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(DeviceDto deviceDto) {
        //1.注册设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapper)>0 ) {
            throw  new BaseException("设备名称重复");
        }
        //2.设备标识是否重复
        LambdaQueryWrapper<Device> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Device::getNodeId, deviceDto.getNodeId());
        if (count(lambdaQueryWrapper)>0 ) {
            throw  new BaseException("设备标识码重复");
        }
        //3.同一位置是否绑定了相同的产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getProductName, deviceDto.getProductName())
                .eq(Device::getLocationType, deviceDto.getLocationType())
        ;
        if ( count(condition)>0){
            throw  new BaseException("该位置已绑定该产品");
        }
        //4.注册设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withNodeId(deviceDto.getNodeId());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withProductId(deviceDto.productKey);
        addDeviceRequest.setBody(body);
        AuthInfo authInfo = new AuthInfo();
        //设置设备秘钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        AddDeviceResponse response= null;
        try {
            response = client.addDevice(addDeviceRequest);
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("注册设备失败");
        }
        //5.本地保存设备信息
        Device device = new Device();
        BeanUtil.copyProperties(deviceDto,device);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        try {
            save(device);
        }catch (Exception e){
            throw new BaseException("保存设备信息失败");
        }
    }
    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response .getHttpStatusCode()!=200){
            throw new BaseException("从物联网获取产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String json = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        if (StrUtil.isNotEmpty(json)){
            return  JSONUtil.toList(json, ProductVo.class);
        }
        return new ArrayList<>();
    }
}
